<?php

namespace app\admin\controller;

use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use app\common\model\Admin;
use app\common\model\Custom as ModelCustom;
use app\common\model\pool\Fpcustom;
use app\common\model\User;
use app\common\model\user\Custom;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use Jdy;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 客户公共池管理
 *
 * @icon fa fa-circle-o
 */
class Custompool extends Backend
{

    /**
     * Custom模型对象
     * @var \app\common\model\Custom
     */
    protected $model = null;
    protected $acctLimit = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Custom;
        $uids = AuthGroupAccess::where('group_id', 10)->column('uid');
        $adminlist = Admin::whereIn('id', $uids)->column('acct_id,nickname');
        $this->assignconfig("adminlist", $adminlist);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'])
                ->where('custom.is_pool', 1)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'mobile']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $has = ModelCustom::where('phone', $params['phone'])->where('id', '<>', $ids)->find();
            if ($has) {
                exception('该客户已存在');
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function allocation($ids = null)
    {
        if (!$ids) {
            $this->error('请选择要分配的销售');
        }
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $time = time();
            // $has = Custom::where('')
            $users = ModelCustom::whereIn('id', $ids)->where('is_send',0)->select();
            $count = 0;
            foreach ($users as $k => $v) {
                $res = Custom::create([
                    'custom_id' => $v['id'],
                    'acct_id' => $v['acct_id'],
                    'channel' => $params['channel'],
                ]);
                $v->is_send = 1;
                $v->save();
                queue('app\common\job\Cancelalloca@custompool', $res->id, 18000, 'cancelalloca1243');

                if ($res) {
                    $count++;
                }
            }

            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (!$count) {
            $this->error(__('未有新的销售可分配'));
        }
        $this->success();
    }

    public function import()
    {
        $acct_id = $this->auth->acct_id;
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $file = $this->request->request('idata');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            $a = 0;
   
            $fieldArr = [
                '手机号' => 'phone',
                '姓名' => 'name',
                '省市区' => 'city',
                '详细地址' => 'address',
                '备注' => 'remark',
                '客户分类' => 'cate',
                '产品类别' => 'product_cate',
                '客户来源平台' => 'source',
            ];


            $insert = [];
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

            $data = [];


            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {

                    $cell = $currentSheet->getCell(\PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($currentColumn) . $currentRow);

                    $val = $cell->getValue();
                    // $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {


                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {

                    $cell = $currentSheet->getCell(\PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($currentColumn) . $currentRow);

                    $val = $cell->getValue();
                    // $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                    if (!empty($data[$currentRow][$currentColumn])) {
                        $val = $data[$currentRow][$currentColumn];
                    }
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }

                if ($row) {
   

                    $uid = ModelCustom::where('phone', $row['phone'])->value('id');
                    if (!$uid) {
                        Db::startTrans();
                        try {
                            $row['is_pool'] = 1;
                            $row['acct_id'] = $acct_id;
                            ModelCustom::create($row);
                            
                            $a++;
                            Db::commit();
                        } catch (\Exception $e) {
                            Db::rollback();
                        }
                    }
                }
            }

            


            //删除导入文件
            @unlink($filePath);
            $this->success("成功+{$a}条", null);
        }
        // parent::import();
        return $this->view->fetch();
        
    }


    /**
     * 按比例分配
     */
    public function rateallocation($ids = null)
    {
        if (!$ids) {
            $this->error('请选择要分配的经销商');
        }
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        // $params = $this->request->post('row/a');
        // if (empty($params)) {
        //     $this->error(__('Parameter %s can not be empty', ''));
        // }
        // $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $time = time();
            $user = User::where('id', $ids)->find();
            if(!$user){
                exception('经销商不存在');
            }
            $total_list = Custom::alias('c')->where('c.channel', $user->id)->field('id,(SELECT IF(sum(total_fee)>500,1,0) from fa_shop_order o where custom_id=c.custom_id and `status`>"0") as fee')->select();

            $total = count($total_list);
            $num = array_sum(array_column($total_list, 'fee')) ?? 0;
    
            //Order::where('custom_id', 'in', $custom_ids)->where('status', '>', 0)->count();
            $rate = $total > 0 ? bcmul($num / $total, 100, 0) : 0;


            $num = Fpcustom::where('acct_id', $this->auth->acct_id)->where('rate', '<=', $rate)->order('rate desc')->find();
            if(!$num){
                exception('没有满足可分配条件');
            }
            $num = $num['num'];
            // $has = Custom::where('')
            $users = ModelCustom::whereIn('acct_id', $this->auth->acct_id)->where('is_send',0)->limit($num)->select();
            $count = 0;
            foreach ($users as $k => $v) {
                $res = Custom::create([
                    'custom_id' => $v['id'],
                    'acct_id' => $v['acct_id'],
                    'channel' => $user->id,
                ]);
                $v->is_send = 1;
                $v->save();
                queue('app\common\job\Cancelalloca@custompool', $res->id, 18000, 'cancelalloca1243');

                if ($res) {
                    $count++;
                }
            }

            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (!$count) {
            $this->error(__('未有新的销售可分配'));
        }
        $this->success();
    }
}
